﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

using System.IO;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.UI.WebControls;
using JM.JCY.BusinessEntity;
using System.Collections.Specialized;


namespace JM.JCY.Common.Utilities
{
    public class JCYSharePointHelper
    {
        static string JCYUrl = System.Configuration.ConfigurationManager.AppSettings["JCYUrl"].ToString();

        #region document libraries & files

        /* 
         * Used within the class file to check if a folder of the specified name exist in a library
         * Returns true if folder exists and false if it doesn't          
         */
        private static bool CheckFolderExists(SPWeb web, string siteName, string listName, string contextID, string albumName)
        {
            bool exists = false;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                if (albumName != "")
                {
                    StringBuilder url = new StringBuilder();
                    url.Append(JCYUrl + "/" + siteName + "/" + listName + "/" + contextID);
                    url = url.Replace("@", string.Empty);
                    SPFolder folder = web.GetFolder(url.ToString());
                    exists = folder.Exists;
                }
                else
                {
                    SPList list = web.Lists[listName];
                    SPFolderCollection folderCol = list.RootFolder.SubFolders;
                    foreach (SPFolder folder in folderCol)
                    {
                        if (folder.Name == contextID)
                        {
                            foreach (SPFolder subFolder in folder.SubFolders)
                            {
                                if (subFolder.Item[SPBuiltInFieldId.FileLeafRef].ToString() == albumName || (subFolder.Item["CustomName"] != null && subFolder.Item["CustomName"].ToString() == albumName))
                                {
                                    exists = true;

                                    break;
                                }
                            }
                        }
                    }
                }
            });
            return exists;
        }

        /*
         * Create a new album folder in a specific asset library and uploads media/pictures under the newly created album folder
         * SiteName
         * ApplicationType (Fun / Heart)
         * ContextId         
         * MediaStream 
         * MediaExtension (Match with MediaStream)
         * MediaTable (1st column: video path, 2nd column: thumbnail path)
         * SharingOption (All / (Blank))
         */
        public static SPOutputs CreateFolderWithUpload(SPInputs inputs)
        {
            SPOutputs outputs = new SPOutputs();
            outputs.IsError = false;
            outputs.Message = "";

            if (inputs.SiteName != null &&
                inputs.ApplicationType != null &&
                inputs.ContextID != null &&
                inputs.SharingOption != null)
            {
                DataTable outputsTable = CreateOutputTable();
                DataRow dr;

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(JCYUrl + "/" + inputs.SiteName))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            string listName = "";
                            if (inputs.ApplicationType == JCYConstant.PhotoAlbum.ApplicationTypeName.PublicName)
                            {
                                listName = JCYConstant.PhotoListName.PublicPhoto;
                            }
                            else if (inputs.ApplicationType == JCYConstant.PhotoAlbum.ApplicationTypeName.WorkgroupName)
                            {
                                listName = JCYConstant.PhotoListName.WorkgroupPhoto;
                            }
                            else if (inputs.ApplicationType == JCYConstant.PhotoAlbum.ApplicationTypeName.CommitteeName)
                            {
                                listName = JCYConstant.PhotoListName.CommitteePhoto;
                            }
                            else
                            {
                                listName = JCYConstant.PhotoListName.PersonalPhoto;
                            }

                            try
                            {
                                //setting the album name based on the sharing option
                                Guid guid = System.Guid.NewGuid();
                                string albumName = guid.ToString();
                                web.AllowUnsafeUpdates = true;
                                SPFolder newFolder;
                                Guid newFolderID = new Guid();

                                SPList list = web.Lists[listName];
                                //if (listName.Equals(JCYConstant.PhotoListName.PublicPhoto))
                                //{
                                //现暂不区分每个部门 或小组,就是所有部门的都放在一个list,所有小组的都放在一个list里面.个人的共公的 也同样处理.
                                newFolder = list.RootFolder.SubFolders.Add(albumName);
                                newFolder.Item.Update();
                                newFolderID = newFolder.UniqueId;
                                dr = outputsTable.NewRow();
                                dr[JCYConstant.SharePointHelper.OutputTablePara.FolderID] = newFolder.UniqueId;
                                outputsTable.Rows.Add(dr);
                                //}
                                //else
                                //{
                                //    SPFolderCollection folderColl = list.RootFolder.SubFolders;
                                //    bool isFound = false;
                                //    foreach (SPFolder folder in folderColl)
                                //    {
                                //        if (folder.Name == inputs.ContextID)
                                //        {
                                //            isFound = true;

                                //            newFolder = folder.SubFolders.Add(albumName);
                                //            newFolder.Item.Update();
                                //            newFolderID = newFolder.UniqueId;
                                //            dr = outputsTable.NewRow();
                                //            dr[JCYConstant.SharePointHelper.OutputTablePara.FolderID] = newFolder.UniqueId;
                                //            outputsTable.Rows.Add(dr);

                                //            break;
                                //        }
                                //    }

                                //    if (isFound == false)
                                //    {
                                //        SPFolder itemFolder = list.RootFolder.SubFolders.Add(inputs.ContextID);
                                //        itemFolder.Item.Update();

                                //        newFolder = itemFolder.SubFolders.Add(albumName);
                                //        newFolder.Item.Update();
                                //        newFolderID = newFolder.UniqueId;
                                //        dr = outputsTable.NewRow();
                                //        dr[JCYConstant.SharePointHelper.OutputTablePara.FolderID] = newFolder.UniqueId;
                                //        outputsTable.Rows.Add(dr);
                                //    }
                                //}


                                //saving of files
                                outputsTable = UploadMedia(web, newFolderID, inputs, outputsTable, outputs);
                                outputs.OutputsTable = outputsTable;
                                web.AllowUnsafeUpdates = false;
                            }
                            catch (Exception ex)
                            {
                                outputs.IsError = true;
                                outputs.Message += ex.Message.ToString() + Environment.NewLine;
                            }
                            finally
                            {
                                if (web != null)
                                    web.Dispose();
                                if (site != null)
                                    site.Dispose();
                            }
                        }
                    }
                });
            }
            else
            {
                outputs.IsError = true;
                outputs.Message += "Invalid inputs." + Environment.NewLine;
            }

            return outputs;
        }

        /*
         * Internal method used to upload media/pictures based on the mediaPath 
         */
        private static DataTable UploadMedia(SPWeb web, Guid newFolderID, SPInputs inputs, DataTable outputsTable, SPOutputs outputs)
        {
            DataRow dr;
            //saving of picture/audio files
            if (inputs.MediaStream != null && inputs.MediaExtension != null)
            {
                for (int i = 0; i < inputs.MediaStream.Count; i++)
                {
                    try
                    {
                        SPFolder folder = web.GetFolder(newFolderID);

                        string extension = inputs.MediaExtension[i];
                        string fileName = DateTime.Now.ToString(JCYConstant.SharePointHelper.FileNameFormat) + i.ToString() + extension;
                        folder.Files.Add(folder.Url + "/" + fileName, inputs.MediaStream[i]);
                        SPFile file = web.GetFile(folder.Url + "/" + fileName);

                        dr = outputsTable.NewRow();
                        dr[JCYConstant.SharePointHelper.OutputTablePara.FolderID] = newFolderID;
                        dr[JCYConstant.SharePointHelper.OutputTablePara.ItemID] = file.UniqueId;
                        dr[JCYConstant.SharePointHelper.OutputTablePara.OriginalImgUrl] = file.ServerRelativeUrl;
                        dr[JCYConstant.SharePointHelper.OutputTablePara.ThumbNailImgUrl] = GetAlternatePicUrl(file.ServerRelativeUrl, JCYConstant.SharePointHelper.PicType.ThumbNail);
                        dr[JCYConstant.SharePointHelper.OutputTablePara.OptimizeImgUrl] = GetAlternatePicUrl(file.ServerRelativeUrl, JCYConstant.SharePointHelper.PicType.Optimized);
                        outputsTable.Rows.Add(dr);
                    }
                    catch (Exception ex)
                    {
                        outputs.IsError = true;
                        outputs.Message += ex.Message.ToString() + Environment.NewLine;
                    }
                }
            }

            //saving of video files
            if (inputs.MediaTable != null)
            {
                for (int i = 0; i < inputs.MediaTable.Rows.Count; i++)
                {
                    try
                    {
                        FileStream fStream = File.OpenRead(inputs.MediaTable.Rows[i][0].ToString());
                        byte[] originalContents = new byte[fStream.Length];
                        fStream.Read(originalContents, 0, (int)fStream.Length);

                        fStream = File.OpenRead(inputs.MediaTable.Rows[i][1].ToString());
                        byte[] thumbnailContents = new byte[fStream.Length];
                        fStream.Read(thumbnailContents, 0, (int)fStream.Length);
                        fStream.Close();

                        SPFolder folder = web.GetFolder(newFolderID);

                        string extension = Path.GetExtension(inputs.MediaTable.Rows[i][0].ToString());
                        string fileName = DateTime.Now.ToString(JCYConstant.SharePointHelper.FileNameFormat);
                        folder.Files.Add(folder.Url + "/" + fileName + extension, originalContents);
                        SPFile originalFile = web.GetFile(folder.Url + "/" + fileName + extension);
                        //SPFile file = web.GetFile(folder.Url + "/" + fileName);

                        extension = Path.GetExtension(inputs.MediaTable.Rows[i][1].ToString());
                        fileName = fileName + "_preview";
                        folder.Files.Add(folder.Url + "/" + fileName + extension, thumbnailContents);
                        SPFile thumbnailFile = web.GetFile(folder.Url + "/" + fileName + extension);

                        dr = outputsTable.NewRow();
                        dr[JCYConstant.SharePointHelper.OutputTablePara.FolderID] = newFolderID;
                        dr[JCYConstant.SharePointHelper.OutputTablePara.ItemID] = originalFile.UniqueId;
                        dr[JCYConstant.SharePointHelper.OutputTablePara.OriginalImgUrl] = originalFile.ServerRelativeUrl;
                        dr[JCYConstant.SharePointHelper.OutputTablePara.ThumbNailImgUrl] = thumbnailFile.ServerRelativeUrl;
                        outputsTable.Rows.Add(dr);

                        //delete from temp folder                        
                        //File.Create(inputs.MediaTable.Rows[i][0].ToString()).Dispose();
                        //File.Delete(inputs.MediaTable.Rows[i][0].ToString());

                        //File.Create(inputs.MediaTable.Rows[i][1].ToString()).Dispose();
                        //File.Delete(inputs.MediaTable.Rows[i][1].ToString());
                    }
                    catch (Exception ex)
                    {
                        outputs.IsError = true;
                        outputs.Message += ex.Message.ToString() + Environment.NewLine;
                    }
                }
            }
            return outputsTable;
        }

        /*
         * For uploading of files
         * SiteName
         * SPFolderId
         * MediaStream 
         * MediaExtension (Match with MediaStream)
         * MediaTable (1st column: video path, 2nd column: thumbnail path)
         * SharingOption (All / (Blank))
         */
        public static SPOutputs UploadMedia(SPInputs inputs)
        {
            SPOutputs outputs = new SPOutputs();
            outputs.IsError = false;
            outputs.Message = "";

            if (inputs.SiteName != null &&
                inputs.SPFolderID != null &&
                inputs.SharingOption != null)
            {
                DataTable outputsTable = CreateOutputTable();
                DataRow dr;

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(JCYUrl + "/" + inputs.SiteName))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;
                            Guid folderID = new Guid(inputs.SPFolderID);

                            //saving of picture/audio files
                            if (inputs.MediaStream != null && inputs.MediaExtension != null)
                            {
                                for (int i = 0; i < inputs.MediaStream.Count; i++)
                                {
                                    try
                                    {
                                        SPFolder folder = web.GetFolder(folderID);

                                        string extension = inputs.MediaExtension[i];
                                        string fileName = DateTime.Now.ToString(JCYConstant.SharePointHelper.FileNameFormat) + extension;
                                        folder.Files.Add(folder.Url + "/" + fileName, inputs.MediaStream[i]);
                                        SPFile file = web.GetFile(folder.Url + "/" + fileName);

                                        dr = outputsTable.NewRow();
                                        dr[JCYConstant.SharePointHelper.OutputTablePara.FolderID] = folderID;
                                        dr[JCYConstant.SharePointHelper.OutputTablePara.ItemID] = file.UniqueId;
                                        dr[JCYConstant.SharePointHelper.OutputTablePara.OriginalImgUrl] = file.ServerRelativeUrl;
                                        dr[JCYConstant.SharePointHelper.OutputTablePara.ThumbNailImgUrl] = GetAlternatePicUrl(file.ServerRelativeUrl, JCYConstant.SharePointHelper.PicType.ThumbNail);
                                        dr[JCYConstant.SharePointHelper.OutputTablePara.OptimizeImgUrl] = GetAlternatePicUrl(file.ServerRelativeUrl, JCYConstant.SharePointHelper.PicType.Optimized);
                                        outputsTable.Rows.Add(dr);
                                    }
                                    catch (Exception ex)
                                    {
                                        outputs.IsError = true;
                                        outputs.Message += ex.Message.ToString() + Environment.NewLine;
                                    }
                                }
                            }

                            //saving of video files
                            #region
                            if (inputs.MediaTable != null)
                            {
                                for (int i = 0; i < inputs.MediaTable.Rows.Count; i++)
                                {
                                    try
                                    {
                                        FileStream fStream = File.OpenRead(inputs.MediaTable.Rows[i][0].ToString());
                                        byte[] originalContents = new byte[fStream.Length];
                                        fStream.Read(originalContents, 0, (int)fStream.Length);

                                        fStream = File.OpenRead(inputs.MediaTable.Rows[i][1].ToString());
                                        byte[] thumbnailContents = new byte[fStream.Length];
                                        fStream.Read(thumbnailContents, 0, (int)fStream.Length);
                                        fStream.Close();

                                        SPFolder folder = web.GetFolder(folderID);

                                        string extension = Path.GetExtension(inputs.MediaTable.Rows[i][0].ToString());
                                        string fileName = DateTime.Now.ToString(JCYConstant.SharePointHelper.FileNameFormat);
                                        folder.Files.Add(folder.Url + "/" + fileName + extension, originalContents);
                                        SPFile originalFile = web.GetFile(folder.Url + "/" + fileName + extension);

                                        extension = Path.GetExtension(inputs.MediaTable.Rows[i][1].ToString());
                                        fileName = fileName + "_preview";
                                        folder.Files.Add(folder.Url + "/" + fileName + extension, thumbnailContents);
                                        SPFile thumbnailFile = web.GetFile(folder.Url + "/" + fileName + extension);

                                        dr = outputsTable.NewRow();
                                        dr[JCYConstant.SharePointHelper.OutputTablePara.FolderID] = folderID;
                                        dr[JCYConstant.SharePointHelper.OutputTablePara.ItemID] = originalFile.UniqueId;
                                        dr[JCYConstant.SharePointHelper.OutputTablePara.OriginalImgUrl] = originalFile.ServerRelativeUrl;
                                        dr[JCYConstant.SharePointHelper.OutputTablePara.ThumbNailImgUrl] = thumbnailFile.ServerRelativeUrl;
                                        outputsTable.Rows.Add(dr);

                                        //delete from temp folder                        
                                        //File.Create(inputs.MediaTable.Rows[i][0].ToString()).Dispose();
                                        //File.Delete(inputs.MediaTable.Rows[i][0].ToString());

                                        //File.Create(inputs.MediaTable.Rows[i][1].ToString()).Dispose();
                                        //File.Delete(inputs.MediaTable.Rows[i][1].ToString());
                                    }
                                    catch (Exception ex)
                                    {
                                        outputs.IsError = true;
                                        outputs.Message += ex.Message.ToString() + Environment.NewLine; ;
                                    }
                                }
                            }
                            #endregion

                            web.AllowUnsafeUpdates = false;
                            outputs.OutputsTable = outputsTable;
                        }
                    }
                });
            }
            else
            {
                outputs.IsError = true;
                outputs.Message += "Invalid inputs." + Environment.NewLine; ;
            }
            return outputs;
        }

        /*
         * For uploading of files to Top Site Images library
         * SiteName
         * MediaStream 
         * MediaExtension (Match with MediaStream)
         * ListName 
         */
        public static SPOutputs UploadMediaTopImages(SPInputs inputs)
        {
            SPOutputs outputs = new SPOutputs();
            outputs.IsError = false;
            outputs.Message = "";

            DataTable outputsTable = CreateOutputTable();
            DataRow dr;

            if (inputs.MediaStream != null && inputs.MediaExtension != null)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(JCYUrl + "/" + inputs.SiteName))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;

                            for (int i = 0; i < inputs.MediaStream.Count; i++)
                            {
                                try
                                {
                                    SPList list = web.Lists[inputs.SPListName];
                                    SPFolder folder = list.RootFolder;

                                    string extension = inputs.MediaExtension[i];
                                    string fileName = DateTime.Now.ToString(JCYConstant.SharePointHelper.FileNameFormat) + extension;
                                    SPFile file = folder.Files.Add(folder.Url + "/" + fileName, inputs.MediaStream[i]);

                                    dr = outputsTable.NewRow();
                                    dr[JCYConstant.SharePointHelper.OutputTablePara.ItemID] = file.UniqueId;
                                    dr[JCYConstant.SharePointHelper.OutputTablePara.OriginalImgUrl] = file.ServerRelativeUrl;
                                    dr[JCYConstant.SharePointHelper.OutputTablePara.ThumbNailImgUrl] = GetAlternatePicUrl(file.ServerRelativeUrl, JCYConstant.SharePointHelper.PicType.ThumbNail);
                                    dr[JCYConstant.SharePointHelper.OutputTablePara.OptimizeImgUrl] = GetAlternatePicUrl(file.ServerRelativeUrl, JCYConstant.SharePointHelper.PicType.Optimized);
                                    outputsTable.Rows.Add(dr);
                                }
                                catch (Exception ex)
                                {
                                    outputs.IsError = true;
                                    outputs.Message += ex.Message.ToString() + Environment.NewLine;
                                }
                                finally
                                {
                                    web.AllowUnsafeUpdates = false;

                                    if (web != null)
                                        web.Dispose();
                                    if (site != null)
                                        site.Dispose();
                                }
                            }
                        }
                    }
                });
            }
            outputs.OutputsTable = outputsTable;

            return outputs;
        }

        /*
         * Deletes a file in Top Site Images library
         * SiteName
         * MediaUrl  
         * SPListName
         */
        public static SPOutputs RemoveMediaTopImages(SPInputs inputs)
        {
            SPOutputs outputs = new SPOutputs();
            outputs.IsError = false;
            outputs.Message = "";

            if (inputs.MediaUrl != null)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(JCYUrl + "/" + inputs.SiteName))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;

                            try
                            {
                                SPList list = web.Lists[inputs.SPListName];
                                SPFolder folder = list.RootFolder;

                                folder.Files.Delete(GetOriginalPicUrl(inputs.MediaUrl));
                            }
                            catch (Exception ex)
                            {
                                outputs.IsError = true;
                                outputs.Message += ex.Message.ToString() + Environment.NewLine;
                            }
                            finally
                            {
                                web.AllowUnsafeUpdates = false;

                                if (web != null)
                                    web.Dispose();
                                if (site != null)
                                    site.Dispose();
                            }
                        }
                    }
                });
            }
            return outputs;
        }

        #region UpdateAlbum
        /*
         * Update the name of an album
         * SiteName
         * SPFolderID        
         * SharingOption
         
        public static SPOutputs UpdateAlbum(SPInputs inputs)
        {
            SPOutputs outputs = new SPOutputs();
            outputs.IsError = false;
            outputs.Message = "";

            if (inputs.SiteName != null &&
                inputs.SPFolderID != null) //&&
            //inputs.NewAlbumName != null)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(JCYUrl + "/" + inputs.SiteName))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;
                            try
                            {
                                Guid spFolderID = new Guid(inputs.SPFolderID);
                                SPFolder folder = web.GetFolder(spFolderID);
                                string albumName = folder.Name;
                                //if (inputs.SharingOption == "")
                                //    albumName += "_U";

                                SPList list = web.Lists[folder.ParentListId];

                                folder.Item.Update();
                                string contextFolderName = folder.ParentFolder.Name.ToString();

                                if (inputs.SharingOption == JCYConstant.NewsfeedParams.SharingOption.Within)
                                {
                                    //setting all user permissions from the folder 
                                    SPListItem listItem = list.Folders[spFolderID];
                                    if (!listItem.HasUniqueRoleAssignments)
                                        listItem.BreakRoleInheritance(false);

                                    SPRoleAssignmentCollection assignmentCol = listItem.RoleAssignments;
                                    for (int i = assignmentCol.Count - 1; i >= 0; i--)
                                    {
                                        assignmentCol.Remove(i);
                                    }

                                    //set permission to only the sharepoint user group                                                                                                                       
                                    SPGroup group = web.ParentWeb.SiteGroups[contextFolderName];
                                    SPRoleDefinition definition = web.RoleDefinitions.GetByType(SPRoleType.Reader);
                                    SPRoleAssignment assignment = new SPRoleAssignment(group);
                                    assignment.RoleDefinitionBindings.Add(definition);
                                    listItem.RoleAssignments.Add(assignment);
                                }
                                else
                                {
                                    SPListItem listItem = list.Folders[spFolderID];
                                    listItem.ResetRoleInheritance();

                                    SPListItemCollection listItemCol = listItem.ListItems;
                                    foreach (SPItem item in listItemCol)
                                    {
                                        item.ResetRoleInheritance();
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                outputs.IsError = true;
                                outputs.Message += ex.Message.ToString() + Environment.NewLine; ;
                            }
                            finally
                            {
                                web.AllowUnsafeUpdates = false;

                                if (web != null)
                                    web.Dispose();
                                if (site != null)
                                    site.Dispose();
                            }
                        }
                    }
                });
            }
            else
            {
                outputs.IsError = true;
                outputs.Message += "Invalid inputs." + Environment.NewLine;
            }
            return outputs;
        }
        */
        #endregion
        /*
         * For deletion of folders in a SharePoint Library
         * SiteName
         * SPFolderID
         */
        public static SPOutputs RemoveAlbum(SPInputs inputs)
        {
            SPOutputs outputs = new SPOutputs();
            outputs.IsError = false;
            outputs.Message = "";

            if (inputs.SiteName != null &&
                inputs.SPFolderID != null)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(JCYUrl + "/" + inputs.SiteName))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;
                            try
                            {
                                Guid spFolderID = new Guid(inputs.SPFolderID);
                                SPFolder folder = web.GetFolder(spFolderID);
                                for (int i = 0; i < folder.Files.Count; i++)
                                {
                                    folder.Files[i].Delete();
                                }
                                folder.Delete();
                            }
                            catch (Exception ex)
                            {
                                outputs.IsError = true;
                                outputs.Message = ex.Message.ToString();
                            }
                            finally
                            {
                                web.AllowUnsafeUpdates = false;

                                if (web != null)
                                    web.Dispose();
                                if (site != null)
                                    site.Dispose();
                            }
                        }
                    }
                });
            }
            else
            {
                outputs.IsError = true;
                outputs.Message += "Invalid inputs." + Environment.NewLine;
            }
            return outputs;
        }

        /*
         * Deletes a file in SharePoint library
         * SiteName
         * SPFolderID
         * SPListItemID
         */
        public static SPOutputs RemoveMedia(SPInputs inputs)
        {
            SPOutputs outputs = new SPOutputs();
            outputs.IsError = false;
            outputs.Message = "";

            if (inputs.SiteName != null &&
                inputs.SPFolderID != null &&
                inputs.SPListItemID != null)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(JCYUrl + "/" + inputs.SiteName))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;
                            try
                            {
                                Guid spFolderID = new Guid(inputs.SPFolderID);
                                Guid spListItemID = new Guid(inputs.SPListItemID);

                                SPFolder folder = web.GetFolder(spFolderID);
                                SPList list = web.Lists[folder.ParentListId];
                                SPListItem listItem = list.Items[spListItemID];
                                string fileName = Path.GetFileNameWithoutExtension(listItem.File.Name);
                                listItem.Delete();

                                SPFile file = web.GetFile(site.Url + folder.ServerRelativeUrl + "/" + fileName + "_preview" + ".jpg");
                                if (file.Exists)
                                    file.Delete();
                            }
                            catch (Exception ex)
                            {
                                outputs.IsError = true;
                                outputs.Message = ex.Message.ToString();
                            }
                            finally
                            {
                                web.AllowUnsafeUpdates = false;

                                if (web != null)
                                    web.Dispose();
                                if (site != null)
                                    site.Dispose();
                            }
                        }
                    }
                });
            }
            else
            {
                outputs.IsError = true;
                outputs.Message += "Invalid inputs." + Environment.NewLine;
            }
            return outputs;
        }

        /*
         * Internal method to instantiate the outputs table
         */
        private static DataTable CreateOutputTable()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("FolderID");
            dt.Columns.Add("ItemID");
            dt.Columns.Add("OriginalImgUrl");
            dt.Columns.Add("ThumbNailImgUrl");
            dt.Columns.Add("OptimizeImgUrl");

            return dt;
        }

        /*
         * Used to generate the thumbnail and optimized url in the asset library for saving during an upload
         * Returns the url based on the type: ThumbNail/Optimized
         */
        private static string GetAlternatePicUrl(string originalUrl, string type)
        {
            string url = originalUrl;
            string newUrl = "";

            string[] urlArr = originalUrl.Split('/');
            string fileName = urlArr[urlArr.Length - 1];
            fileName = fileName.Replace(".", "_");
            fileName += ".jpg";

            for (int i = 0; i < urlArr.Length - 1; i++)
            {
                if (i != 0)
                    newUrl += "/";
                newUrl += urlArr[i];
            }

            if (type == JCYConstant.SharePointHelper.PicType.ThumbNail)
                newUrl = newUrl + "/" + "_t";
            else if (type == JCYConstant.SharePointHelper.PicType.Optimized)
                newUrl = newUrl + "/" + "_w";

            return newUrl + "/" + fileName;
        }

        /*
         * Used to generate the original url in the asset library based on the thumbnail url
         * Returns the original url
         */
        private static string GetOriginalPicUrl(string thumbNailUrl)
        {
            string url = thumbNailUrl;
            string originalUrl = "";

            string[] urlArr = url.Split('/');
            string fileName = urlArr[urlArr.Length - 1].Substring(0, urlArr[urlArr.Length - 1].LastIndexOf('.'));
            int extStart = fileName.LastIndexOf('_');
            string ext = fileName.Substring(extStart).Replace('_', '.');
            fileName = fileName.Substring(0, extStart) + ext;

            for (int i = 0; i < urlArr.Length - 1; i++)
            {
                if (urlArr[i] != "_t")
                {
                    originalUrl += urlArr[i] + "/";
                }
            }

            return originalUrl + fileName;
        }

        /*
         * Create new context folder
         * SiteName
         * ContextID
         */
        public static SPOutputs CreateContextFolder(SPInputs inputs)
        {
            SPOutputs outputs = new SPOutputs();
            outputs.IsError = false;
            outputs.Message = "";

            if (inputs.SiteName != null &&
                inputs.ContextID != null)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(JCYUrl + "/" + inputs.SiteName))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;
                            try
                            {
                                string[] listName = { "FunLib", "HeartLib" };
                                for (int i = 0; i < listName.Length; i++)
                                {
                                    SPList list = web.Lists[listName[i]];
                                    if (CheckFolderExists(web, inputs.SiteName, listName[i], inputs.ContextID, "") == false)
                                    {
                                        list.EnableFolderCreation = true;
                                        list.Update();

                                        SPListItem listItem = list.Items.Add("", SPFileSystemObjectType.Folder, inputs.ContextID);
                                        listItem.Update();

                                        ////remove other permissions
                                        //if (!listItem.HasUniqueRoleAssignments)
                                        //    listItem.BreakRoleInheritance(false);

                                        //SPRoleAssignmentCollection assignmentCol = listItem.RoleAssignments;
                                        //for (int j = assignmentCol.Count - 1; j >= 0; j--)
                                        //{
                                        //    assignmentCol.Remove(j);
                                        //}

                                        ////set read permission to all users
                                        //SPRoleDefinition definition = web.RoleDefinitions.GetByType(SPRoleType.Reader);
                                        //SPRoleAssignment assignment = new SPRoleAssignment("NT AUTHORITY\\authenticated users", null, null, null);
                                        //assignment.RoleDefinitionBindings.Add(definition);
                                        //listItem.RoleAssignments.Add(assignment);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                outputs.IsError = true;
                                outputs.Message += ex.Message.ToString();
                            }
                            finally
                            {
                                web.AllowUnsafeUpdates = false;

                                if (web != null)
                                    web.Dispose();
                                if (site != null)
                                    site.Dispose();
                            }
                        }
                    }
                });
            }
            else
            {
                outputs.IsError = true;
                outputs.Message += "Invalid inputs." + Environment.NewLine;
            }

            return outputs;
        }

        #endregion

        #region groups and permission
        /*
         * For the creation sharepoint groups
         * ContextID
         */
        public static SPOutputs CreateGroup(SPInputs inputs)
        {
            SPOutputs outputs = new SPOutputs();
            outputs.IsError = false;
            outputs.Message = "";

            if (inputs.ContextID != null)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(JCYUrl))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;
                            try
                            {
                                web.SiteGroups.Add(inputs.ContextID, web.CurrentUser, null, "");
                                SPGroup group = web.SiteGroups[inputs.ContextID];
                                SPRoleDefinition definition = web.RoleDefinitions.GetByType(SPRoleType.Reader);
                                SPRoleAssignment assignment = new SPRoleAssignment(group);
                                assignment.RoleDefinitionBindings.Add(definition);
                                web.RoleAssignments.Add(assignment);
                                web.Update();

                                outputs.GroupID = group.ID;
                            }
                            catch (Exception ex)
                            {
                                outputs.IsError = true;
                                outputs.Message += ex.Message.ToString();
                            }
                            finally
                            {
                                web.AllowUnsafeUpdates = false;

                                if (web != null)
                                    web.Dispose();
                                if (site != null)
                                    site.Dispose();
                            }
                        }
                    }
                });
            }
            else
            {
                outputs.IsError = true;
                outputs.Message += "Invalid inputs." + Environment.NewLine;
            }
            return outputs;
        }

        /*
         * Delete SharePoint Group
         * ContextID
         */
        public static SPOutputs RemoveGroup(SPInputs inputs)
        {
            SPOutputs outputs = new SPOutputs();
            outputs.IsError = false;
            outputs.Message = "";

            if (inputs.ContextID != null)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(JCYUrl))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;
                            try
                            {
                                web.SiteGroups.Remove(inputs.ContextID);
                                web.Update();

                            }
                            catch (Exception ex)
                            {
                                outputs.IsError = true;
                                outputs.Message += ex.Message.ToString();
                            }
                            finally
                            {
                                web.AllowUnsafeUpdates = false;

                                if (web != null)
                                    web.Dispose();
                                if (site != null)
                                    site.Dispose();
                            }
                        }
                    }
                });
            }

            return outputs;
        }

        /*
         * Adding users into the designated sharepoint group
         * ContextID
         * UserID (SharePoint)
         */
        public static SPOutputs AddUserToGroup(SPInputs inputs)
        {
            SPOutputs outputs = new SPOutputs();
            outputs.IsError = false;
            outputs.Message = "";

            if (inputs.ContextID != null)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(JCYUrl))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;
                            try
                            {
                                SPGroup group = web.Groups[inputs.ContextID];

                                if (inputs.UserID != null)
                                {
                                    foreach (string userID in inputs.UserID)
                                    {
                                        SPUser user = web.EnsureUser(userID);
                                        if (user != null)
                                        {
                                            group.AddUser(user);
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                outputs.IsError = true;
                                outputs.Message = ex.Message.ToString();
                            }
                            finally
                            {
                                web.AllowUnsafeUpdates = false;

                                if (web != null)
                                    web.Dispose();
                                if (site != null)
                                    site.Dispose();
                            }
                        }
                    }
                });
            }
            else
            {
                outputs.IsError = true;
                outputs.Message += "Invalid inputs." + Environment.NewLine;
            }
            return outputs;
        }

        /*
         * Remove users from the designated sharepoint group
         * ContextID   
         * UserID (SharePoint)
         */
        public static SPOutputs AddUserToGroup(SPInputs inputs, string UserID)
        {
            SPOutputs outputs = new SPOutputs();
            outputs.IsError = false;
            outputs.Message = "";

            if (inputs.ContextID != null)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(JCYUrl))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;
                            try
                            {
                                SPGroup group = web.Groups[inputs.ContextID];


                                if (UserID != null)
                                {
                                    // foreach (string userID in inputs.UserID)
                                    // {
                                    SPUser user = web.EnsureUser(UserID);
                                    if (user != null)
                                    {
                                        group.AddUser(user);
                                    }
                                    // }
                                }
                            }
                            catch (Exception ex)
                            {
                                outputs.IsError = true;
                                outputs.Message = ex.Message.ToString();
                            }
                            finally
                            {
                                web.AllowUnsafeUpdates = false;

                                if (web != null)
                                    web.Dispose();
                                if (site != null)
                                    site.Dispose();
                            }
                        }
                    }
                });
            }
            else
            {
                outputs.IsError = true;
                outputs.Message += "Invalid inputs." + Environment.NewLine;
            }
            return outputs;
        }
        public static SPOutputs RemoveUsersFromGroup(SPInputs inputs)
        {
            SPOutputs outputs = new SPOutputs();
            outputs.IsError = false;
            outputs.Message = "";

            if (inputs.ContextID != null)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(JCYUrl))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;
                            try
                            {
                                SPGroup group = web.Groups[inputs.ContextID];

                                if (inputs.UserID != null)
                                {
                                    foreach (string userID in inputs.UserID)
                                    {
                                        SPUser user = web.EnsureUser(userID);
                                        if (user != null)
                                        {
                                            group.RemoveUser(user);
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                outputs.IsError = true;
                                outputs.Message = ex.Message.ToString();
                            }
                            finally
                            {
                                web.AllowUnsafeUpdates = false;

                                if (web != null)
                                    web.Dispose();
                                if (site != null)
                                    site.Dispose();
                            }
                        }
                    }
                });
            }
            else
            {
                outputs.IsError = true;
                outputs.Message += "Invalid inputs." + Environment.NewLine;
            }

            return outputs;
        }
        /*
       * Remove a SharePoint group from a list item permission list
       * SPListItemID
       * SPGroup
       */
        public static SPOutputs RemoveAllGroupPermissionFromListItem(SPInputs inputs)
        {
            SPOutputs outputs = new SPOutputs();
            outputs.IsError = false;
            outputs.Message = "";

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;
                        try
                        {
                            SPList list = web.Lists[JCYConstant.MOHipedia.PageLibraryName];
                            SPListItem listItem = list.GetItemById(Convert.ToInt32(inputs.SPListItemID));
                            if (!listItem.HasUniqueRoleAssignments)
                                listItem.BreakRoleInheritance(false);

                            SPRoleAssignmentCollection assignmentCol = listItem.RoleAssignments;
                            for (int i = assignmentCol.Count - 1; i >= 0; i--)
                            {
                                assignmentCol.Remove(i);
                            }
                        }
                        catch (Exception ex)
                        {
                            outputs.IsError = true;
                            outputs.Message += ex.Message.ToString();
                        }
                        finally
                        {
                            web.AllowUnsafeUpdates = false;

                            if (web != null)
                                web.Dispose();
                            if (site != null)
                                site.Dispose();
                        }
                    }
                }
            });

            return outputs;
        }

        /*
         * Update a SharePoint group from a list item permission list
         * SPListItemID
         * SPGroup
         * PermissionType         
         */
        public static SPOutputs UpdateGroupPermissionForListItem(SPInputs inputs)
        {
            SPOutputs outputs = new SPOutputs();
            outputs.IsError = false;
            outputs.Message = "";

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;
                        try
                        {
                            SPList list = web.Lists[JCYConstant.MOHipedia.PageLibraryName];
                            SPListItem listItem = list.GetItemById(Convert.ToInt32(inputs.SPListItemID));
                            if (!listItem.HasUniqueRoleAssignments)
                                listItem.BreakRoleInheritance(false);

                            //set permission to only the sharepoint user group                                                                                                                       
                            SPGroup group = web.SiteGroups[inputs.SPGroup];
                            SPRoleDefinition definition = web.RoleDefinitions.GetByType(SPRoleType.Reader);
                            if (inputs.PermissionType == JCYConstant.SharePointPermission.PermissionType.Contribute.ToString())
                                definition = web.RoleDefinitions.GetByType(SPRoleType.Contributor);
                            SPRoleAssignment assignment = new SPRoleAssignment(group);
                            assignment.RoleDefinitionBindings.Add(definition);
                            listItem.RoleAssignments.Add(assignment);
                        }
                        catch (Exception ex)
                        {
                            outputs.IsError = true;
                            outputs.Message += ex.Message.ToString();
                        }
                        finally
                        {
                            web.AllowUnsafeUpdates = false;

                            if (web != null)
                                web.Dispose();
                            if (site != null)
                                site.Dispose();
                        }
                    }
                }
            });

            return outputs;
        }
        #endregion

        #region mohipedia
        public static SPOutputs CheckWikiExists(SPInputs inputs)
        {
            SPOutputs outputs = new SPOutputs();
            outputs.IsError = false;
            outputs.Message = "";

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        try
                        {
                            SPList list = web.Lists[JCYConstant.MOHipedia.PageLibraryName];
                            foreach (SPListItem listItem in list.Items)
                            {
                                if (listItem["Title"].ToString() == inputs.PageName)
                                {
                                    outputs.IsError = true;
                                    break;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            outputs.IsError = true;
                            outputs.Message += ex.Message.ToString();
                        }
                        finally
                        {
                            web.AllowUnsafeUpdates = false;

                            if (web != null)
                                web.Dispose();
                            if (site != null)
                                site.Dispose();
                        }
                    }
                }
            });
            return outputs;
        }




        /*
         * Gets list id based on a listitem
         */
        private static string GetListID(string listName)
        {
            string listID = "";
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists[listName];
                        listID = list.ID.ToString();
                    }
                }
            });
            return listID;
        }

        /*
         * Gets wiki categories of a wiki page
         */
        public static string GetWikiCategory(string listItemUrl)
        {
            string wikiCategories = "";
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPListItem listItem = web.GetListItem(listItemUrl);
                        wikiCategories = listItem["Wiki Categories"].ToString();
                    }
                }
            });
            return wikiCategories;
        }

        #endregion

        public static string UploadPicFile(FileUpload fileupload, string fileName, string listName)
        {
            string url = string.Empty;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        if (fileupload.HasFile == true)
                        {
                            string filePath = fileupload.PostedFile.FileName;
                            if (filePath != "")
                            {
                                string fileExtension = filePath.Substring(filePath.LastIndexOf(".") + 1).ToLower();
                                string fileTile = string.Format("{0}.{1}", fileName, fileExtension);
                                SPDocumentLibrary DocLib = GetPictureLibrary(listName);
                                SPListItem DocRow = DocLib.Items.Add(DocLib.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.File);
                                SPFolder folder = DocLib.RootFolder;
                                folder.ParentWeb.AllowUnsafeUpdates = true;
                                folder.Files.Add(DocLib.RootFolder.ServerRelativeUrl + "/" + fileTile, fileupload.FileBytes, true);
                                DocLib.Update();
                                folder.ParentWeb.AllowUnsafeUpdates = false;

                                SPFile File = SPContext.Current.Web.GetFile(folder.Url + "/" + fileName + "." + fileExtension);
                                url = GetAlternatePicUrl(File.ServerRelativeUrl, JCYConstant.SharePointHelper.PicType.ThumbNail);
                            }
                        }
                    }
                }
            });

            return url;
        }

        public static string UploadPublishedFile(FileUpload fileupload, string fileName, string listName)
        {
            string url = string.Empty;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        if (fileupload.HasFile == true)
                        {
                            string filePath = fileupload.PostedFile.FileName;
                            if (filePath != "")
                            {
                                string fileExtension = filePath.Substring(filePath.LastIndexOf(".") + 1).ToLower();
                                string fileTile = string.Format("{0}.{1}", fileName, fileExtension);
                                SPDocumentLibrary DocLib = GetPictureLibrary(listName);
                                SPListItem DocRow = DocLib.Items.Add(DocLib.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.File);
                                SPFolder folder = DocLib.RootFolder;
                                folder.ParentWeb.AllowUnsafeUpdates = true;
                                folder.Files.Add(DocLib.RootFolder.ServerRelativeUrl + "/" + fileTile, fileupload.FileBytes, true);
                                DocLib.Update();
                                folder.ParentWeb.AllowUnsafeUpdates = false;

                                SPFile File = SPContext.Current.Web.GetFile(folder.Url + "/" + fileName + "." + fileExtension);
                                url = File.Url;
                            }
                        }
                    }
                }
            });

            return url;
        }

        // add by Hong Liang 2012-05-02
        public static string UploadFileToAttachment(FileUpload fileupload, string fileName, string listName)
        {
            string url = string.Empty;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        if (fileupload.HasFile == true)
                        {
                            string filePath = fileupload.PostedFile.FileName;
                            if (filePath != "")
                            {
                                string fileExtension = filePath.Substring(filePath.LastIndexOf(".") + 1).ToLower();
                                string fileTile = string.Format("{0}.{1}", fileName, fileExtension);
                                SPDocumentLibrary DocLib = GetDocumentLibrary(listName);
                                SPListItem DocRow = DocLib.Items.Add(DocLib.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.File);
                                SPFolder folder = DocLib.RootFolder;
                                folder.ParentWeb.AllowUnsafeUpdates = true;
                                folder.Files.Add(DocLib.RootFolder.ServerRelativeUrl + "/" + fileTile, fileupload.FileBytes, true);
                                DocLib.Update();
                                folder.ParentWeb.AllowUnsafeUpdates = false;

                                SPFile File = SPContext.Current.Web.GetFile(folder.Url + "/" + fileName + "." + fileExtension);
                                // update by Hong Liang to update title field 2012-05-03
                                web.AllowUnsafeUpdates = true;

                                SPListItem destItem = File.Item;
                                destItem.File.CheckOut();
                                destItem["标题"] = fileName;
                                
                                destItem.UpdateOverwriteVersion();
                                destItem.File.CheckIn(string.Empty, SPCheckinType.MinorCheckIn);
                                web.ParserEnabled = true;
                                web.Update();

                                web.AllowUnsafeUpdates = false;
                                url = File.Url;
                            }
                        }
                    }
                }
            });
            return url;
        }

        public static SPDocumentLibrary GetDocumentLibrary(string listName)
        {
            string listPath = String.Empty;
            listPath = listName;
            listPath = listPath.Replace(@"\", @"/");
            string[] paths = listPath.Split(new char[] { ',', ';', '|' });
            if (paths.Length >= 2)
            {
                using (SPWeb web = new SPSite(JCYUrl).OpenWeb(paths[0].TrimStart(new char[] { '/' })))
                {
                    return (SPDocumentLibrary)web.GetList(paths[1]);
                }

            }
            else
            {

                using (SPWeb web = new SPSite(JCYUrl).OpenWeb())
                {
                    return (SPDocumentLibrary)web.GetList(paths[0]);
                }

            }
        }

        public static SPPictureLibrary GetPictureLibrary(string listName)
        {
            string listPath = String.Empty;
            listPath = listName;
            listPath = listPath.Replace(@"\", @"/");
            string[] paths = listPath.Split(new char[] { ',', ';', '|' });
            if (paths.Length >= 2)
            {
                //Edit by Gary, memory leaking when new SPSite (not disposed)
                // using (SPWeb web = new SPSite(SPContext.Current.Site.Url).OpenWeb(paths[0].TrimStart(new char[] { '/' })))
                using (SPWeb web = new SPSite(JCYUrl).OpenWeb(paths[0].TrimStart(new char[] { '/' })))
                {
                    return (SPPictureLibrary)web.GetList(paths[1]);
                }
                //SPSite siteCollection = SPContext.Current.Site;
                //SPWeb oWeb = SPContext.Current.Web;
                //return (SPPictureLibrary)oWeb.GetList(paths[1]);
            }
            else
            {
                //Edit by Gary, memory leaking when new SPSite (not disposed)
                //using (SPWeb web = new SPSite(SPContext.Current.Site.Url).OpenWeb())
                using (SPWeb web = new SPSite(JCYUrl).OpenWeb())
                {
                    return (SPPictureLibrary)web.GetList(paths[0]);
                }
                //SPSite siteCollection = SPContext.Current.Site;
                //SPWeb oWeb = SPContext.Current.Web;
                //return (SPPictureLibrary)oWeb.GetList(paths[0]);
            }
        }

        #region 检察院内部报表

        //绑定SPListView [自侦案件安全办案情况对照检查表]并根据承办人和填表人筛选
        public static void BindListViewToZJ(string currentAccount, string listName, ListView listView, SPQuery query)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb web = site.OpenWeb("MyDept"))
                    {
                        SPList list = web.Lists[listName];
                        listView.ListId = list.ID.ToString();

                        SPViewFieldCollection viewFieldColl = list.Views["MyView"].ViewFields;
                        StringCollection strColl = new StringCollection();
                        foreach (var item in viewFieldColl)
                        {
                            strColl.Add(item.ToString());
                        }


                        if (!SPViewIsExist(currentAccount, list))
                        {
                            web.AllowUnsafeUpdates = true;
                            list.Views.Add(currentAccount, strColl, query.Query, 30, true, false);
                            web.AllowUnsafeUpdates = false;
                        }
                        else
                        {
                            SPView view = list.Views[currentAccount];
                            view.Query = query.Query;
                            web.AllowUnsafeUpdates = true;
                            view.Update();
                            web.AllowUnsafeUpdates = false;
                        }

                        listView.ViewId = list.Views[currentAccount].ID.ToString();
                    }
                }
            });
        }

        public static bool SPViewIsExist(string viewName, SPList list)
        {
            try
            {
                list.Views[viewName].ToString();
                return true;
            }
            catch (Exception)
            {

                return false;
            }

        }


        #endregion

        public static Guid CreateDocumentLibrary(string docName, string docDesc, SPListTemplateType templateType)
        {
            using (SPSite site = new SPSite(JCYUrl))
            {
                using (SPWeb myWeb = site.OpenWeb())
                {
                    Guid listId = new Guid();
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        myWeb.AllowUnsafeUpdates = true;
                        listId = myWeb.Lists.Add(docName, docDesc, templateType);
                        myWeb.Update();
                        myWeb.AllowUnsafeUpdates = false;

                    });
                    return listId;
                }
            }

        }
    }

    public class SPInputs
    {
        private string siteName;
        private string applicationType;
        private string listName;
        private string contextID;
        private string albumName;
        private List<byte[]> mediaStream;
        private List<string> mediaExtension;
        private DataTable mediaTable;
        private string mediaUrl;
        private string sharingOption;
        private string spFolderID;
        private string spListItemID;
        private List<string> userID;
        private string spGroup;
        private string permissionType;
        //mohipedia
        //private string pageName;

        //public string SiteName { get; set; }

        //public string ApplicationType { get; set; }

        //public string ContextID { get; set; }

        //public string AlbumName { get; set; }

        //public List<byte[]> MediaStream { get; set; }

        //public List<string> MediaExtension { get; set; }

        //public DataTable MediaTable { get; set; }

        //public string MediaUrl { get; set; }

        //public string SharingOption { get; set; }

        //public string SPFolderID { get; set; }

        //public string SPListName { get; set; }

        //public string SPListItemID { get; set; }

        //public List<string> UserID { get; set; }

        //public string PageName { get; set; }

        public string SPListName { get; set; }
        private string pageName;

        public string SiteName { get; set; }

        public string ApplicationType { get; set; }

        public string ListName { get; set; }

        public string ContextID { get; set; }

        public string AlbumName { get; set; }

        public List<byte[]> MediaStream { get; set; }

        public List<string> MediaExtension { get; set; }

        public DataTable MediaTable { get; set; }

        public string MediaUrl { get; set; }

        public string SharingOption { get; set; }

        public string SPFolderID { get; set; }

        public string SPListItemID { get; set; }

        public List<string> UserID { get; set; }

        public string SPGroup { get; set; }

        public string PermissionType { get; set; }

        public string PageName { get; set; }
    }

    public class SPOutputs
    {
        private DataTable outputsTable;
        private bool isError;
        private string message;
        private int groupID;
        //mohipedia
        private string listItemID;

        public DataTable OutputsTable { get; set; }

        public bool IsError { get; set; }

        public string Message { get; set; }

        public int GroupID { get; set; }

        public string ListItemID { get; set; }
    }




}

